import React, { useEffect, useRef } from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism-tomorrow.css';
import type { EditorMode } from '../../types';
import './CodeEditor.css';

interface CodeEditorProps {
  mode: EditorMode;
  latex: string;
  onLatexChange: (latex: string) => void;
  onCursorChange?: () => void;
  editorRef: React.RefObject<HTMLTextAreaElement | null>;
}

/**
 * 代码编辑器组件 - 用于编辑LaTeX代码，支持语法高亮
 */
export const CodeEditor: React.FC<CodeEditorProps> = ({
  latex,
  mode,
  onLatexChange,
  onCursorChange,
  editorRef
}) => {
  const highlightRef = useRef<HTMLPreElement>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);

  // 注册LaTeX语言高亮
  useEffect(() => {
    // 简单的LaTeX高亮定义
    if (!Prism.languages.latex) {
      Prism.languages.latex = {
        'comment': /%.*/,
        'command': {
          pattern: /\\[a-zA-Z@]+/,
          alias: 'function'
        },
        'bracket': {
          pattern: /[{}()\[\]]/,
          alias: 'punctuation'
        },
        'math-symbol': {
          pattern: /[=+\-*/^≠≤≥±×÷]/,
          alias: 'operator'
        },
        'number': /\b\d+(?:\.\d+)?\b/,
        'text': /[^\\{}()\[\]=+\-*/^≠≤≥±×÷\d\s%.]+/
      };
    }
  }, []);

  // 处理语法高亮
  useEffect(() => {
    if (highlightRef.current && mode === 'code') {
      // 转义HTML特殊字符
      const escapedLatex = latex
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
      
      // 应用语法高亮
      highlightRef.current.innerHTML = Prism.highlight(
        escapedLatex,
        Prism.languages.latex,
        'latex'
      );
    }
  }, [latex, mode]);

  // 同步滚动
  const handleScroll = () => {
    if (editorRef.current && highlightRef.current) {
      highlightRef.current.scrollTop = editorRef.current.scrollTop;
      highlightRef.current.scrollLeft = editorRef.current.scrollLeft;
    }
  };

  // 自动调整文本区域高度
  useEffect(() => {
    if (editorRef.current && mode === 'code') {
      editorRef.current.style.height = 'auto';
      editorRef.current.style.height = Math.min(editorRef.current.scrollHeight, 400) + 'px';
    }
  }, [latex, mode, editorRef]);

  if (mode !== 'code') {
    return null;
  }

  return (
    <div className="code-editor-wrapper" ref={wrapperRef}>
      {/* 语法高亮层 */}
      <pre className="code-highlight" ref={highlightRef} aria-hidden="true">
        <code className="language-latex"></code>
      </pre>
      
      {/* 实际的文本编辑区域 */}
      <textarea
        ref={editorRef}
        className="code-textarea"
        value={latex}
        onChange={(e) => onLatexChange(e.target.value)}
        onScroll={handleScroll}
        onKeyDown={onCursorChange}
        onKeyUp={onCursorChange}
        onMouseUp={onCursorChange}
        placeholder="在此输入LaTeX代码..."
        spellCheck={false}
        autoComplete="off"
        autoCorrect="off"
        autoCapitalize="off"
        tabIndex={0}
      />
      
      {/* 行号显示 */}
      <div className="line-numbers">
        {latex.split('\n').map((_, index) => (
          <div key={index} className="line-number">{index + 1}</div>
        ))}
      </div>
    </div>
  );
};

export default CodeEditor;